import md5 from 'md5';
import pako from "pako";
import numeral from 'numeral';
import Big from "big.js";
import polyfill from 'Base64';
const { atob, btoa } = polyfill;
function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}

//时间戳转换成日期时间
function js_date_time(unixtime) {
	var date = new Date(unixtime * 1000);
	var y = date.getFullYear();
	var m = date.getMonth() + 1;
	m = m < 10 ? ('0' + m) : m;
	var d = date.getDate();
	d = d < 10 ? ('0' + d) : d;
	var h = date.getHours();
	h = h < 10 ? ('0' + h) : h;
	var minute = date.getMinutes();
	var second = date.getSeconds();
	minute = minute < 10 ? ('0' + minute) : minute;
	second = second < 10 ? ('0' + second) : second;
	return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second; //年月日时分秒
	// return y + '-' + m + '-' + d + ' ' + h + ':' + minute;

}

var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};
const sortObjByKey = function(obj) {
	const keys = Object.keys(obj).sort();
	const newObj = []
	for (let i = 0; i < keys.length; i++) {
		const index = keys[i];
		newObj.push(obj[index]);
	}
	return newObj;
}
/**
 * @description 签名生成
 */
const signatureFormat = function(apikey = '', json = null, timestamp) {
	if (json == null) return '';
	const JsonValueArray = sortObjByKey(json);
	let signature = `${apikey}${JsonValueArray.join('')}${timestamp}`;
	console.log('未加密签名:', signature);
	// console.log('中文编码后的', encodeURIComponent(signature));
	// console.log('md5后', md5(signature));
	signature = encodeURIComponent(signature);
	return md5(signature);
}
export function comboParameter(json = null) {
	if (json == null) return '';
	const timestamp = Date.parse(new Date());
	const apikey = "b117df30868bd1f5f280c36d50fdf21a";
	const newSignature = signatureFormat(apikey.trim(), json, timestamp);
	return { ...json,
		ts: timestamp,
		tsign: newSignature
	};
}
function handleCodePoints(array) {
      var CHUNK_SIZE = 0x8000; // arbitrary number here, not too small, not too big
      var index = 0;
      var length = array.length;
      var result = '';
      var slice;
      var arr = [];
      for (var i = 0, _i = array.length; i < _i; i++) {
          arr[i] = array[i];
     }
     while (index < length) {
         slice = arr.slice(index, Math.min(index + CHUNK_SIZE, length)); // `Math.min` is not really necessary here I think
         result += String.fromCharCode.apply(null, slice);
         index += CHUNK_SIZE;
     }
     return result;
 }
function ungzip (b64Data) {
  let strData = atob(b64Data);
  // Convert binary string to character-number array
  let charData = strData.split("").map(function(x) {
    return x.charCodeAt(0);
  });
  // Turn number array into byte-array
  let binData = new Uint8Array(charData);
  // // unzip
  let data = pako.inflate(binData);
  // Convert gunzipped byteArray back to ascii string:
  strData = handleCodePoints(data);
  return decodeURIComponent(strData);
};
function gzip (str) {
  let binaryString = pako.gzip(encodeURIComponent(str), {
    to: "string"
  });
  return btoa(binaryString);
};
/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.img标签添加style属性：max-width:100%;height:auto
 * 3.修改所有style里的width属性为max-width:100%
 * 4.去掉<br/>标签
 * @param html
 * @returns {void|string|*}
 */
function formatRichText(html){
  let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
    return match;
  });
  newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
    return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  newContent = newContent.replace(/\<img/gi, '< img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
  return newContent;
}

function formatDateTime(date) {
	var date = new Date();
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var day = date.getDate();

	var hour = date.getHours();
	var minute = date.getMinutes();
	var second = date.getSeconds();


	return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
}

function formatNumber(n) {
	n = n.toString();
	return n[1] ? n : '0' + n;
}

function getPhoneNumber(phone) {
	uni.makePhoneCall({
		phoneNumber: phone //仅为示例
	});
}
/**
 * @desc 由经纬度计算两点之间的距离，la为latitude缩写，lo为longitude
 * @param la1 第一个坐标点的纬度
 * @param lo1 第一个坐标点的经度
 * @param la2 第二个坐标点的纬度
 * @param lo2 第二个坐标点的经度
 * @return (int)s   返回距离(单位千米或公里)
 * @tips 注意经度和纬度参数别传反了，一般经度为0~180、纬度为0~90
 * 具体算法不做解释，有兴趣可以了解一下球面两点之间最短距离的计算方式
 */
function distance(la1, lo1, la2, lo2) {
	var La1 = la1 * Math.PI / 180.0;
	var La2 = la2 * Math.PI / 180.0;
	var La3 = La1 - La2;
	var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(
		Lb3 / 2), 2)));
	s = s * 6378.137;
	s = Math.round(s * 10000) / 10000;
	s = s.toFixed(2);
	return s;
}
//精度计算
function amount(s, n = 100) {
	let x = new Big(s);
	let y = x.times(n);
	return y.toFixed();
}

function money(float, format = "0.00") {
	return numeral(float / 100).format(format);
}
function judge(item,memberType){
	let finallyPrice = 0;
	if(memberType==1||memberType==2){
		finallyPrice = money(item.svip_price)
	}else if(memberType==3){
		finallyPrice = money(item.vip_price) 
	}else{
		finallyPrice = money(item.sale_price)
	}
	return Number(finallyPrice) ;
}

module.exports = {
	formatTime,
	formatLocation,
	dateUtils,
	comboParameter,
	formatDateTime,
	getPhoneNumber,
	distance,
	ungzip,
	gzip,
	js_date_time,
	amount,
	money,
	formatRichText,
	judge
}
